package com.dullong.firedocmanager.lucene4;

import java.io.IOException;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.NumericRangeQuery;
import org.springframework.stereotype.Service;

@Service
public class LuceneIndexService extends LuceneBase {

	public void LuceneIndexService() {

	}

	/**
	 * 优化索引库
	 * 
	 * @param objClass
	 * @throws IOException
	 */
	public synchronized void optimize() throws IOException {
		IndexWriter writer = getIndexWriter();
		try {
			writer.forceMerge(1);
			writer.commit();
		} finally {
			// writer.close();
			// writer = null;
		}
	}

	/**
	 * 批量添加索引
	 * 
	 * @param docs
	 * @throws IOException
	 */
	public synchronized int add(List<? extends Searchable> objs)
			throws IOException {
		if (objs == null || objs.size() == 0)
			return 0;
		int doc_count = 0;
		IndexWriter writer = getIndexWriter();
		try {
			for (Searchable obj : objs) {
				Document doc = SearchHelper.obj2doc(obj);
				writer.addDocument(doc);
				doc_count++;
			}
			writer.commit();
		} finally {
			// writer.close();
			// writer = null;
		}
		return doc_count;
	}

	/**
	 * 批量删除索引
	 * 
	 * @param docs
	 * @throws IOException
	 */
	public synchronized int delete(List<? extends Searchable> objs)
			throws IOException {
		if (objs == null || objs.size() == 0)
			return 0;
		int doc_count = 0;
		IndexWriter writer = getIndexWriter();
		try {
			for (Searchable obj : objs) {
				NumericRangeQuery<Long> longRange = NumericRangeQuery
						.newLongRange("ID", obj.id(), obj.id(), true, true);
				writer.deleteDocuments(longRange);
				doc_count++;
			}
			writer.commit();
		} finally {
			// writer.close();
			// writer = null;
		}
		return doc_count;
	}

	/**
	 * 删除所有索引
	 * 
	 * @throws IOException
	 */
	public synchronized void deleteAll() throws IOException {
		IndexWriter writer = getIndexWriter();
		writer.deleteAll();
		writer.commit();
	}

	public synchronized int delete(Long... docids) throws IOException {
		if (docids == null || docids.length == 0)
			return 0;
		int doc_count = 0;
		IndexWriter writer = getIndexWriter();
		try {
			for (Long docid : docids) {
				NumericRangeQuery<Long> longRange = NumericRangeQuery
						.newLongRange("ID", docid, docid, true, true);
				writer.deleteDocuments(longRange);
				doc_count++;
			}
			writer.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// writer.close();
			// writer = null;
		}
		return doc_count;
	}

	/**
	 * 批量更新索引
	 * 
	 * @param docs
	 * @throws IOException
	 */
	public synchronized void update(List<? extends Searchable> objs)
			throws IOException {
		delete(objs);
		add(objs);
	}

	public void close() throws IOException {
		IndexWriter writer = getIndexWriter();
		writer.close();
		writer = null;
	}
}
